﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mimoza.Transport;

namespace Mimoza.DBLayer.Transport
{
    class ConnectionObjectStore<TObject>
        where TObject : class, IDisposable, new()
    {
        public ConnectionObjectStore()
        {
        }

        public void Add(TObject obj, Connection conn)
        {
            lock (m_collections)
            {
                m_collections[conn] = obj;
                conn.CloseHandler += OnConnectionClose;
            }
        }

        public void Delete(Connection conn)
        {
            lock (m_collections)
            {
                if (m_collections.ContainsKey(conn))
                {
                    m_collections[conn].Dispose();
                    m_collections.Remove(conn);
                }
            }
        }

        public TObject Get(Connection conn)
        {
            lock (m_collections)
            {
                if (m_collections.ContainsKey(conn))
                {
                    return m_collections[conn];
                }
            }

            return null;
        }

        public IEnumerable<TObject> GetAll()
        {
            lock (m_collections)
            {
                foreach (KeyValuePair<Connection, TObject> pair in m_collections)
                {
                    yield return pair.Value;
                }
            }
        }

        void OnConnectionClose(Connection conn)
        {
            TObject foundObj = null;
            lock (m_collections)
            {
                foreach (KeyValuePair<Connection, TObject> pair in m_collections)
                {
                    if (pair.Key == conn)
                    {
                        foundObj = pair.Value;
                        Delete(pair.Key);
                        break;
                    }
                }
            }
        }

        Dictionary<Connection, TObject> m_collections = new Dictionary<Connection,TObject>();
    }
}
